package com.redis.service;

import com.redis.entity.Student;
import org.redisson.api.*;
import org.redisson.client.codec.StringCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CKC
 * @DateTime 2021/11/14 15:12
 */
@Component
@SuppressWarnings("all")
public class RedissonStudy {

    @Autowired
    private RedissonClient redisson;

    //通用对象
    public void test1() {
        RBucket<Student> studentRBucket = redisson.getBucket("student");
        studentRBucket.set(new Student().setName("ckc").setAge(23).setEmail("374899270@qq.com"));
        if (studentRBucket.isExists()) {
            System.out.println(studentRBucket.get());
        }
        //批量操作多个对象
        RBuckets buckets = redisson.getBuckets();
        Map<String, Object> objectMap = buckets.get("keyName1", "keyName2", "...");
        //....

        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        buckets.set(objectObjectHashMap);//保存全部
        //利用redis的事务特性，同时保存所有通用对象，如果其中某一个已经存在，则放弃所有
        buckets.trySet(objectObjectHashMap);

    }

    //二进制流
    public void test2() throws IOException {
        RBinaryStream binaryStream = redisson.getBinaryStream("key");
        OutputStream outputStream = binaryStream.getOutputStream();//写入redis流
        byte[] output = "我爱你哟~！".getBytes();
        outputStream.write(output);


        InputStream inputStream = binaryStream.getInputStream();//java读取
        byte[] read = new byte[1024];
        while (inputStream.read(read, 0, read.length) != -1) {
            System.out.println(new String(read));
        }
    }

    public void test3() {
        RStream<Object, Object> key = redisson.getStream("key", new StringCodec(StandardCharsets.UTF_8));

    }

}
